#include "ColorMap.h"

#include <QDebug>
#include <QFile>
#include <QImageReader>
#include <QPainter>

#include <algorithm/shared/tool/imageSaver/ColorBar.h>
#include <algorithm/shared/tool/imageSaver/ImageSaver.h>

using namespace solar;

ColorMap::ColorMap(QQuickItem* parent)
    : QQuickPaintedItem(parent), receiver_height_(1), receiver_width_(1), colorbar_height_(300),
      colorbar_width_(20), colorbar_ticks_num_(6), png_bar_dist_(10), img_resolution_x_(200),
      img_resolution_y_(200), original_img_width_(30), original_img_height_(400), font_size_(8),
      x_offset_(20), y_offset_(20), visible_(false)
{
    img_ = QImage("file:./flux_map.png");
    update();
}

void ColorMap::setMinMax(float min, float max)
{
    // min_value_ = min;
    // max_value_ = max;
    ImageSaver::colorbar.setMinMax(min, max);
    // updateColors();
    this->update();
}
// float ColorMap::getMaxValue()
// {
//     return max_value_;
// }
// void ColorMap::setMaxValue(float max_value)
// {
//     max_value_ = max_value;
//     this->update();
// }

auto ColorMap::getColor(float val, float min_val, float max_val) -> QColor
{
    rgb8_pixel_t pixel = ImageSaver::colorbar.getColorAtValue(val, min_val, max_val);
    QColor color((int)pixel[0], (int)pixel[1], (int)pixel[2]);
    return color;
}

/**
 * TODO::use QImageReader to load .png
 */
void ColorMap::paint(QPainter* painter)
{
    if (painter == nullptr)
    {
        return;
    }
    if (visible_)
    {
        qDebug() << "---- visible = " << visible_;
        return;
    }

    int scaled_img_height = (int)(original_img_height_ * scale_);
    int scaled_img_width = img_resolution_x_ * 1.0 / img_resolution_y_ * scaled_img_height;
    // int scaled_img_width = (int)(original_img_width_ * scale_);

    // -------------picture----------------------
    // QString img_path = "./flux_map.png";
    // if(!img_.load(img_path))
    // {
    //     qDebug("can not load img");
    //     QFile file(img_path);
    //     file.open(QIODevice::Unbuffered | QIODevice::ReadOnly );
    //     if(! img_.loadFromData(file.readAll()))
    //     {
    //         qDebug("can not load img * 2");
    //     }
    //     file.close();
    // }

    QImageReader reader;
    reader.setDecideFormatFromContent(true);
    reader.setScaledSize(QSize(scaled_img_width, scaled_img_height));
    reader.setFileName("./flux_map.png");
    if (reader.canRead())
    {
        if (!reader.read(&img_))
        {
            QString str_error = reader.errorString();
            qDebug() << "can not read image: " << str_error;
            return;
        }
    }

    // img_ = img_.scaled(scaled_img_width, scaled_img_height, Qt::KeepAspectRatio);
    int img_width_ = img_.width();
    int img_height_ = img_.height();
    qDebug() << "altered: img_width=" << img_width_ << "  img_height=" << img_height_;
    painter->drawPixmap(0 + x_offset_, 0 + y_offset_, QPixmap::fromImage(img_));

    // --------------colorbar------------------
    colorbar_height_ = img_height_;
    for (int i = 0; i < colorbar_height_; i++)
    {
        QRect rect(img_width_ + png_bar_dist_ + x_offset_, colorbar_height_ - i + y_offset_,
                   colorbar_width_, 1);
        auto color = getColor(i, 0, colorbar_height_);
        painter->fillRect(rect, color);
        // qDebug() <<"  colorbar   i = " << i <<"  color = " << color;
    }

    float min_value = ImageSaver::colorbar.getMin();
    float max_value = ImageSaver::colorbar.getMax();
    for (int i = 0; i < colorbar_ticks_num_; i++)
    {
        QString strValue;
        strValue = QString::asprintf("%.2f", min_value + i * (max_value - min_value) /
                                                             (colorbar_ticks_num_ - 1));
        QFont font;
        font.setFamily("Microsoft Yahei");
        font.setPointSize(font_size_);
        QFontMetrics fm(font);
        QRect rec = fm.boundingRect(strValue);

        int text_width = rec.width();
        int text_height = rec.height();
        // std::cout <<" ----------- text_width = " << text_width <<std::endl;
        // std::cout <<" ----------- text_height = " << text_height <<std::endl;
        // qDebug() <<" strValue = " << strValue;
        QRect text_rect(img_width_ + png_bar_dist_ + colorbar_width_ + 5 + +x_offset_,
                        colorbar_height_ - text_height / 2 -
                            (colorbar_height_ / (colorbar_ticks_num_ - 1)) * i + +y_offset_,
                        text_width + 20, text_height + 10);
        painter->drawText(text_rect, strValue);
    }

    // ------------y ticks--------------------
    QRect ytick_rect(-1 + x_offset_, 0 + y_offset_, 1, img_height_);
    painter->fillRect(ytick_rect, QColor("red"));
    for (int i = 0; i < yticks_num_; i++)
    {
        int tick_y_location = img_height_ - (img_height_ / (yticks_num_ - 1) * i);
        QRect minitick_rect(-1 + x_offset_ - 2, tick_y_location + y_offset_, 3, 1);
        painter->fillRect(minitick_rect, QColor("red"));

        QString tick_val;
        tick_val =
            QString::asprintf("%.2f", receiver_height_ / ((float)yticks_num_ - 1.0) * (float)i);
        QFont font;
        font.setFamily("Microsoft Yahei");
        font.setPointSize(font_size_);
        QFontMetrics fm(font);
        QRect rec = fm.boundingRect(tick_val);
        int text_width = rec.width();
        int text_height = rec.height();

        QRect text_rect(-text_width - 20 + x_offset_, tick_y_location - text_height / 2 + y_offset_,
                        text_width + 20, text_height + 10);
        painter->drawText(text_rect, tick_val);
    }
    // ------------x ticks---------------------------
    QRect xtick_rect(0 + x_offset_, img_height_ + y_offset_, img_width_, 1);
    painter->fillRect(xtick_rect, QColor("red"));
    for (int i = 0; i < xticks_num_; i++)
    {
        int tick_x_location = img_width_ / (xticks_num_ - 1) * i;
        QRect minitick_rect(tick_x_location + x_offset_ - 1, img_height_ + y_offset_, 1, 3);
        painter->fillRect(minitick_rect, QColor("red"));

        QString tick;
        tick = QString::asprintf("%.2f", receiver_width_ / (xticks_num_ - 1) * i);
        QFont font;
        font.setFamily("Microsoft Yahei");
        font.setPointSize(font_size_);
        QFontMetrics fm(font);
        QRect rec = fm.boundingRect(tick);
        int text_width = rec.width();
        int text_height = rec.height();

        QRect text_rect(img_width_ / (xticks_num_ - 1) * i - text_width / 2 + x_offset_,
                        img_height_ + 5 + y_offset_, text_width + 20, text_height + 10);
        painter->drawText(text_rect, tick);
    }
}
void ColorMap::rePaint()
{
    this->update();
    std::cout << " repaint!!!" << std::endl;
}
void ColorMap::updateImage(const QImage& image)
{
    img_ = QImage("/home/liu/Git_resposity/solar/solar_software/solar_2/build/flux_map.png");
    // img_ = image;
    update();
}

void ColorMap::setVisible()
{
    visible_ = true;
    std::cout << " set visible = " << visible_ << std::endl;
    // update();
}
